package com.vhall.component.controller.ctrl;


import com.alibaba.fastjson.JSONObject;
import com.vhall.component.controller.ctrl.facade.CtrlAdmFacade;
import com.vhall.component.entity.ctrl.AnchorExtendsEntityDTO;
import com.vhall.component.entity.ctrl.vo.ConnectNumSetReqVo;
import com.vhall.component.entity.ctrl.vo.ConnectNumVo;
import com.vhall.component.entity.ctrl.vo.ConnectQueueAddReqVo;
import com.vhall.component.entity.ctrl.vo.GetConnectNumRspVO;
import com.vhall.component.framework.common.annotation.VhallComponent;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.annotation.TokenAuth;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.support.Token;
import com.vhall.component.plugin.common.support.TokenThreadLocal;
import com.vhall.component.service.ctrl.CtrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;


/**
 * 并发控制组件 - Admin 端接口
 *
 * @author xuyongzheng
 * @link https://factory.vhallyun.com/fe/document/be/use/%E5%B9%B6%E5%8F%91%E6%8E%A7%E5%88%B6.html
 * @since 2021/5/17 上午11:12
 **/
@VhallComponent
public class CtrlAdmController implements CtrlAdmFacade {

    @Autowired
    private CtrlService ctrlService;

    @Value("${vhall.connect.appMax}")
    private Integer maxConnectCount;

    @TokenAuth("sys:ctrl:add")
    @Override
    public AnchorExtendsEntityDTO setConnectNum(ConnectNumSetReqVo vo) {
        TokenThreadLocal.getToken();
        int appMax = maxConnectCount;
        if (vo.getConnectNum() > appMax) {
            throw new BusinessException(BizErrorCode.BIZ_CONCURRENT_OVERFLOW);
        }
        return ctrlService.createOrUpdate(vo);
    }

    @TokenAuth("sys:ctrl:info")
    @Override
    public GetConnectNumRspVO getConnectNum(@Validated ConnectNumVo vo) {
        GetConnectNumRspVO rspVO = new GetConnectNumRspVO();
        TokenThreadLocal.getToken();
        AnchorExtendsEntityDTO entity = ctrlService.findByAccountId(vo.getAccountId());
        int num = 0;
        if (null != entity) {
            num = entity.getConnectNum();
        }
        rspVO.setNum(num);
        rspVO.setMaxConnectCount(maxConnectCount);
        return rspVO;
    }

    @TokenAuth("sys:ctrl")
    @Override
    public Boolean queueAdd(@Validated ConnectQueueAddReqVo vo) {
        Token account = TokenThreadLocal.getToken();
        Integer accountId = account.getAccountId();
        return ctrlService.queueAdd(accountId, vo.getIlId());
    }

    @Override
    public JSONObject getSysConnectInfo() {
        return ctrlService.getSysConnectInfo();
    }
}
